package com.enjoylearning.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.base.model.PageResult;
import com.enjoylearning.content.model.po.CoursePublish;
import com.enjoylearning.learning.feignclient.ContentServiceClient;
import com.enjoylearning.learning.mapper.XcChooseCourseMapper;
import com.enjoylearning.learning.mapper.XcCourseTablesMapper;
import com.enjoylearning.learning.model.dto.MyCourseTableParams;
import com.enjoylearning.learning.model.dto.XcChooseCourseDto;
import com.enjoylearning.learning.model.dto.XcCourseTablesDto;
import com.enjoylearning.learning.model.po.XcChooseCourse;
import com.enjoylearning.learning.model.po.XcCourseTables;
import com.enjoylearning.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {

    @Autowired
    private XcChooseCourseMapper xcChooseCourseMapper;
    @Autowired
    private XcCourseTablesMapper xcCourseTablesMapper;
    @Autowired
    private ContentServiceClient contentServiceClient;

    @Transactional
    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long CourseId) {
        if (userId == null || CourseId == null) {
            XueChengPlusException.cast("信息为空");
        }
        //判断课程是否收费
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(CourseId);
        if (coursepublish == null) {
            XueChengPlusException.cast("课程信息不存在");
        }
        String charge = coursepublish.getCharge();
        //免费直接添加到选课表、我的课程表
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        if (charge.equals("201000")){
            //向选课记录表插入
            xcChooseCourse = addFreeCoruse(userId, coursepublish);
            //向我的课程表插入
            XcCourseTables xcCourseTables = addCourseTabls(xcChooseCourse);
        }else {
            //收费则添加到选课记录表
            xcChooseCourse = addChargeCoruse(userId, coursepublish);
        }
        //判断学生学习资格
        XcCourseTablesDto learningStatus = getLearningStatus(userId, CourseId);
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
        BeanUtils.copyProperties(xcChooseCourse, xcChooseCourseDto);
        xcChooseCourseDto.setLearnStatus(learningStatus.getLearnStatus());
        return xcChooseCourseDto;
    }

    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {
        //查询我的课程表，查不到表示没有选课
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>()
                .eq(XcCourseTables::getUserId, userId)
                .eq(XcCourseTables::getCourseId, courseId));
        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        if (null == xcCourseTables) {
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }
        //查到了检查是否过期
        LocalDateTime validtimeEnd = xcCourseTables.getValidtimeEnd();
        if (validtimeEnd.isBefore(LocalDateTime.now())) {
            //已过期
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        }
        //未过期，可正常学习
        xcCourseTablesDto.setLearnStatus("702001");
        return xcCourseTablesDto;
    }

    @Transactional
    @Override
    public boolean saveChooseCourseSuccess(String chooseCourseId) {
        //根据课程id查询课程表
        XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectById(chooseCourseId);
        if (xcChooseCourse == null) {
            log.debug("接收到购买课程的消息，根据选课的id无法从数据库找到选课记录{}", chooseCourseId);
            return false;
        }
        //判断是否为未支付
        String status = xcChooseCourse.getStatus();
        if (status.equals("701002"))
        {
            //未支付，更新选课记录状态为支付成功
            xcChooseCourse.setStatus("701001");
            int i = xcChooseCourseMapper.updateById(xcChooseCourse);
            if (i <= 0){
                log.debug("添加选课记录失败，{}", chooseCourseId);
                XueChengPlusException.cast("添加选课记录失败");
            }
            //向我的课程表插入课程
            XcCourseTables xcCourseTables = addCourseTabls(xcChooseCourse);
            return true;
        }
        return false;
    }

    @Override
    public PageResult<XcCourseTables> mycoursetable(MyCourseTableParams params) {
        int page = params.getPage();
        int size = params.getSize();
        Page<XcCourseTables> courseTablesPage = new Page<>(page, size);
        LambdaQueryWrapper<XcCourseTables> wapper = new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, params.getUserId());
        Page<XcCourseTables> xcCourseTablesPage = xcCourseTablesMapper.selectPage(courseTablesPage, wapper);
        return new PageResult<XcCourseTables>(xcCourseTablesPage.getRecords(),xcCourseTablesPage.getSize(),page,size);
    }

    //添加免费课程,免费课程加入选课记录表、我的课程表
    public XcChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {
        Long courseId = coursepublish.getId();
        //判断是否已经存在
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(new LambdaQueryWrapper<XcChooseCourse>()
                .eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getCourseId, courseId)
                .eq(XcChooseCourse::getOrderType,"700001")//免费课程
                .eq(XcChooseCourse::getStatus,"701001"));//选课成功
        //存在直接返回
        if (!xcChooseCourses.isEmpty()) {
            return xcChooseCourses.get(0);
        }
        //不存在插入信息
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        BeanUtils.copyProperties(coursepublish, xcChooseCourse);
        xcChooseCourse.setCourseId(courseId);
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700001");//免费课程
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setValidDays(365);
        xcChooseCourse.setStatus("701001");//选课成功
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());//有效期开始时间
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));//有效期结束时间
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 1) {
            XueChengPlusException.cast("添加课程失败");
        }
        return xcChooseCourse;
    }

    //添加收费课程
    public XcChooseCourse addChargeCoruse(String userId,CoursePublish coursepublish){
        Long courseId = coursepublish.getId();
        //判断是否已经存在
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(new LambdaQueryWrapper<XcChooseCourse>()
                .eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getCourseId, courseId)
                .eq(XcChooseCourse::getOrderType,"700002")//免费课程
                .eq(XcChooseCourse::getStatus,"701002"));//选课成功
        //存在直接返回
        if (!xcChooseCourses.isEmpty()) {
            return xcChooseCourses.get(0);
        }
        //不存在插入信息
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        BeanUtils.copyProperties(coursepublish, xcChooseCourse);
        xcChooseCourse.setCourseId(courseId);
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700002");//免费课程
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setValidDays(coursepublish.getValidDays());
        xcChooseCourse.setStatus("701002");//选课成功
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());//有效期开始时间
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));//有效期结束时间
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 1) {
            XueChengPlusException.cast("添加课程失败");
        }
        return xcChooseCourse;
    }
    //添加到我的课程表
    public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse) {
        //选课记录完成且未过期可以添加课程到课程表
        String status = xcChooseCourse.getStatus();
        if (!"701001".equals(status)) {
            XueChengPlusException.cast("选课未成功，无法添加到课程表");
        }
        //查询我的课程表
        XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
        if (xcCourseTables != null) {
            return xcCourseTables;
        }
        XcCourseTables xcCourseTablesNew = new XcCourseTables();
        xcCourseTablesNew.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTablesNew.setUserId(xcChooseCourse.getUserId());
        xcCourseTablesNew.setCourseId(xcChooseCourse.getCourseId());
        xcCourseTablesNew.setCompanyId(xcChooseCourse.getCompanyId());
        xcCourseTablesNew.setCourseName(xcChooseCourse.getCourseName());
        xcCourseTablesNew.setCreateDate(LocalDateTime.now());
        xcCourseTablesNew.setValidtimeStart(xcChooseCourse.getValidtimeStart());
        xcCourseTablesNew.setValidtimeEnd(xcChooseCourse.getValidtimeEnd());
        xcCourseTablesNew.setCourseType(xcChooseCourse.getOrderType());
        int insert = xcCourseTablesMapper.insert(xcCourseTablesNew);
        if (insert <= 1) {
            XueChengPlusException.cast("添加‘我的课程’失败");
        }
        return xcCourseTables;
    }

    //获取我的选课记录
    public XcCourseTables getXcCourseTables(String userId,Long courseId){
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId).eq(XcCourseTables::getCourseId, courseId));
        return xcCourseTables;

    }
}
